<?php


namespace App\Services\Game;

use App\DTOS\Admin\SaleDTO;
use App\Models\Game\GameChannel;
use App\Models\Game\Sale;
use App\Services\RestClientService;
use App\Utils\MyLog;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;
use Nette\Utils\Random;

class SaleService
{

    private RestClientService $resetClientService;

    /**
     * SaleService constructor.
     * @param RestClientService $resetClientService
     */
    public function __construct(RestClientService $resetClientService)
    {
        $this->resetClientService = $resetClientService;
    }


    /**
     * @param SaleDTO $dto
     * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator
     */
    public function paginate(SaleDTO $dto){
        $page = $dto->getPage();
        $limit = $dto->getLimit();
        $model = Sale::query();
        $code = $dto->getCode();
        $channel= $dto->getGamechannel();
        if ($code){
            $model->where('code',$code);
        }
        if ($channel){
            $model->where('channel',$channel);
        }
        return $model->orderByDesc('id')->paginate($limit,'*','page',$page);
    }

    /**  生成并且插入唯一的邀请码
     * @param $num
     * @return bool
     */
    public function gen($num,$channelId,$name){

        $uniqueCodes = $this->genUniqueCodes($num,$channelId);
        MyLog::info('新的账号名字'.json_encode($uniqueCodes));
        $inserts = [];
        foreach ($uniqueCodes as $code){
            $inserts[] = [
                'code'=>$code,
                'password'=>mt_rand(100000,999999),
                'created_at'=>now()->format("Y-m-d H:i:s"),
                'channel'=>$channelId,
                'channelName'=>$name
            ];
        }
        Sale::query()->insert($inserts);
    }

    public function flushSaleAdmin(){

        $response = $this->resetClientService->post("http://task:9502/sale/flushAdmin");

        Log::info("flush response:" . json_encode($response));

    }

    /** 生成唯一邀请码
     * @param int $num 数量
     */
    private function genUniqueCodes(int $num,int $channelId)
    {
        $str ='';
        MyLog::info('传入的参数'.json_encode($channelId));
        $gameChannel=GameChannel::query()->where('id',$channelId)->first();
        if($gameChannel && $gameChannel->nick) {
            $str=$gameChannel->nick;
        }

        $existingCodes = Sale::query()->pluck('code')->toArray();
        $newCodes = [];

        for ($i = 0; $i < $num; $i++) {
            $strArr = str_split('ABCDEFGHIJKLMNOPQRSTUVWXYZ');
            shuffle($strArr);
            $letters = join('', array_only($strArr,[0,1,2]));

            $digits =  str_repeat(mt_rand(0,9),3);
            $newCode = $letters . $digits;

            while (in_array($newCode, $existingCodes)) {
                $strArr = str_split('ABCDEFGHIJKLMNOPQRSTUVWXYZ');
                shuffle($strArr);
                $letters = join('', array_only($strArr,[0,1,2]));
                $digits = str_repeat(mt_rand(0,9),3);
                $newCode = $letters . $digits;
            }

            $newCodes[] = $str . $newCode;
            $existingCodes[] = $newCode;
        }

        return $newCodes;
    }

    private function genCodes($num){
        $arr = [];
        for ($i=0;$i<$num;$i++){
            $strArr = str_split('ABCDEFGHIJKLMNOPQRSTUVWXYZ');
            shuffle($strArr);
            $prefix = join('', array_only($strArr,[0,1,2]));
            $lastFix = str_repeat(mt_rand(0,9),3);
            $name = $prefix.$lastFix;
            $existsCodes = Sale::query()->where('code',$name)->pluck('code')->toArray(); //已经存在的codes
            if( $existsCodes!=null && !count($existsCodes)>1 ){
                $arr[] = $name;
            }
        }
        return $arr;
    }

    /**
     * @param $id
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function getById($id){
        return Sale::query()->find($id);
    }
}
